package com.jack.xiaoer.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.jack.xiaoer.entity.Product;
import com.jack.xiaoer.service.ProductService;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.validator.Groups;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/13.
 */
@Validated
@RestController
@RequestMapping("/product")
public class ProductController extends BaseController {

    @Autowired
    private ProductService productService;

    @PostMapping("/create")
    public AjaxResponse create(@RequestBody @Validated({Groups.ProductCreate.class}) Optional<Product> product, BindingResult bindingResult) {
        AjaxResponse error = commonValidate(product, bindingResult);
        if (null != error) {
            return error;
        }

        Product productSaved = productService.createProduct(product);
        if (productSaved == null)
            return AjaxResponse.fail("新添商品失败");

        return AjaxResponse.success("新添商品成功", productSaved);
    }

    @GetMapping("/list/{shopId}/{cateId}/{pageNum}/{pageSize}")
    public AjaxResponse list(@PathVariable Long shopId, @PathVariable Long cateId
            , @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Preconditions.checkArgument(pageNum > 0, "pageNum should be positive");
        Preconditions.checkArgument(pageSize > 0, "pageSize should be positive");

        IPage<Product> productPage = productService.listProduct(shopId, cateId, pageNum, pageSize);

        if (productPage == null) {
            return AjaxResponse.fail("获取商品列表失败");
        }

        return AjaxResponse.success("获取商品列表成功", productPage);
    }

    @ExceptionHandler({IllegalArgumentException.class})
    public AjaxResponse handleIllegalParamters(IllegalArgumentException e) {
        return AjaxResponse.invalid(e.getMessage());
    }

}
